const router = require('koa-router')()
//const { getTodoList,addItem}=require('../dbop/redis')  //解构赋值

const {getTodoList,addItem,deleteItem,updateItem} =require('../service/todo')
//const todolist=[{title:'去公园',isComplete:false},{title:'去商城',isComplete:false},{title:'去运动馆',isComplete:false}]



router.prefix('/api/todo/')
router.get('/', async (ctx, next) => {
  // await ctx.render('index', {
  //   title: 'Hello Koa 2!'
  // })
  ctx.body = 'hello koa2'

})

router.post('/testpost', async (ctx, next) => {
  ctx.body = 'koa2 post'
})


router.post('/additem', async (ctx, next) => {

  const data= ctx.request.body

 // addItem(data)




 const r= await addItem(data)
  //  const jstr=JSON.stringify(data)
  //  redisClient.set('todoitem',jstr)
  // todolist.push(data)
//console.log(r)
ctx.body={id:r.insertId}
  //ctx.body =await getTodoList()  //'koa2 post'
})


router.post('/updateitem', async (ctx, next) => {

  const data= ctx.request.body

 const r= await updateItem(data)
  //  const jstr=JSON.stringify(data)
  //  redisClient.set('todoitem',jstr)
  // todolist.push(data)
//console.log(r)
ctx.body='ok'
  //ctx.body =await getTodoList()  //'koa2 post'
})

router.post('/deleteitem', async (ctx, next) => {

  const {delid}= ctx.request.body

  //todolist.splice(i,1)
 // ctx.body="ok!!!"

  ctx.body=await deleteItem(delid)
 // await addItem(data)
  //  const jstr=JSON.stringify(data)
  //  redisClient.set('todoitem',jstr)
  // todolist.push(data)

//"ok!!!"
  //ctx.body =await getTodoList()  //'koa2 post'
})



router.post('/clearitems', async (ctx, next) => {

  //const data= ctx.request.body

 // todolist.length=0//'000000'

  //todolist.splice(0,1)
 // ctx.body = todolist.length  //'koa2 post'
})



router.get('/getallitems', async (ctx, next) => {
 ctx.body = await getTodoList()  //todolist   // 

// ctx.body=[{
//                   id:2,
//                   completed:false,
//                   title:'ksjkafjkjwekjfkjwfjkle'}]
//testConn()
//ctx.body=[]
})


// router.get('/api/getallitems', async (ctx, next) => {
//   ctx.body = todolist
// })

router.get('/string', async (ctx, next) => {
  ctx.body = 'koa2 string'
})

router.get('/json', async (ctx, next) => {
  ctx.body = {
    title: 'koa2 json'
  }
})

module.exports = router
